<template>
  <div class="file-manager">
    <a-card title="文件管理" size="small">
      <template #extra>
        <a-space>
          <a-button 
            type="primary" 
            size="small" 
            @click="refreshFiles"
            :loading="loading"
          >
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
          <a-button 
            size="small" 
            @click="clearAllFiles"
            :loading="clearingAll"
            danger
          >
            <template #icon><DeleteOutlined /></template>
            清空所有
          </a-button>
        </a-space>
      </template>

      <!-- 文件统计信息 -->
      <div class="file-stats" v-if="files.length > 0">
        <a-space>
          <a-tag color="blue">总计: {{ files.length }}</a-tag>
          <a-tag color="green">使用中: {{ usingCount }}</a-tag>
          <a-tag color="orange">未使用: {{ files.length - usingCount }}</a-tag>
        </a-space>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedFiles.length > 0">
        <a-space>
          <span>已选择 {{ selectedFiles.length }} 个文件</span>
          <a-button 
            size="small" 
            @click="batchMarkAsUsed"
            :loading="batchLoading"
          >
            批量标记使用
          </a-button>
          <a-button 
            size="small" 
            @click="batchUnmarkAsUsed"
            :loading="batchLoading"
          >
            批量取消使用
          </a-button>
          <a-button 
            size="small" 
            @click="selectedFiles = []"
          >
            取消选择
          </a-button>
        </a-space>
      </div>

      <!-- 文件列表 -->
      <div class="file-list" v-if="files.length > 0">
        <a-list 
          :data-source="files || []" 
          :loading="loading"
          size="small"
        >
          <template #renderItem="{ item }">
            <a-list-item v-if="item" class="file-item">
              <div class="file-content">
                <div class="file-selection">
                  <a-checkbox 
                    :checked="selectedFiles.includes(item.id)"
                    @change="toggleFileSelection(item.id)"
                  />
                </div>
                
                <div class="file-info">
                  <div class="file-name">
                    <a-tooltip :title="item.original_name">
                      <span class="name-text">{{ item.original_name }}</span>
                    </a-tooltip>
                    <a-tag 
                      :color="item.used ? 'green' : 'default'" 
                      size="small"
                      class="status-tag"
                    >
                      {{ item.used ? '使用中' : '未使用' }}
                    </a-tag>
                  </div>
                  
                  <div class="file-meta">
                    <a-space size="small">
                      <span class="file-size">{{ formatFileSize(item.size) }}</span>
                      <span class="upload-time">{{ formatTime(item.upload_time) }}</span>
                      <a-tag 
                        size="small" 
                        :color="getFileTypeColor(item.original_name)"
                      >
                        {{ getFileExtension(item.original_name) }}
                      </a-tag>
                    </a-space>
                  </div>
                </div>

                <div class="file-actions">
                  <a-space>
                    <a-button 
                      v-if="!item.used"
                      type="primary" 
                      size="small"
                      @click="markAsUsed(item.id)"
                      :loading="operatingFiles.includes(item.id)"
                    >
                      标记使用
                    </a-button>
                    <a-button 
                      v-else
                      size="small"
                      @click="unmarkAsUsed(item.id)"
                      :loading="operatingFiles.includes(item.id)"
                    >
                      取消使用
                    </a-button>
                    
                    <a-dropdown :trigger="['click']">
                      <a-button size="small" type="text">
                        <template #icon><MoreOutlined /></template>
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click="viewFileInfo(item)">
                            <FileTextOutlined />
                            查看详情
                          </a-menu-item>
                          <a-menu-item @click="reuploadFile(item)">
                            <UploadOutlined />
                            重新上传
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item 
                            @click="deleteFile(item.id, item.original_name)"
                            class="danger-item"
                          >
                            <DeleteOutlined />
                            删除文件
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!loading">
        <a-empty description="暂无上传的文件">
          <template #image>
            <FileOutlined style="font-size: 48px; color: #d9d9d9;" />
          </template>
        </a-empty>
      </div>
    </a-card>

    <!-- 文件详情模态框 -->
    <a-modal
      v-model:open="fileDetailVisible"
      title="文件详情"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedFileDetail">
        <a-descriptions :column="1" bordered size="small">
          <a-descriptions-item label="文件名">
            {{ selectedFileDetail.file_info.original_name }}
          </a-descriptions-item>
          <a-descriptions-item label="本地存储名">
            <a-typography-text copyable>{{ selectedFileDetail.file_info.saved_name }}</a-typography-text>
            <a-tooltip title="这是文件在系统中的实际存储名称，可用于 /read 等命令操作">
              <InfoCircleOutlined style="margin-left: 8px; color: #1890ff;" />
            </a-tooltip>
          </a-descriptions-item>
          <a-descriptions-item label="文件大小">
            {{ formatFileSize(selectedFileDetail.file_info.size) }}
          </a-descriptions-item>
          <a-descriptions-item label="上传时间">
            {{ formatTime(selectedFileDetail.file_info.upload_time) }}
          </a-descriptions-item>
          <a-descriptions-item label="使用状态">
            <a-tag :color="selectedFileDetail.file_info.used ? 'green' : 'default'">
              {{ selectedFileDetail.file_info.used ? '使用中' : '未使用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="文件类型">
            {{ selectedFileDetail.parse_info.file_extension }}
          </a-descriptions-item>
          <a-descriptions-item label="解析支持">
            <a-tag :color="selectedFileDetail.parse_info.is_supported ? 'green' : 'red'">
              {{ selectedFileDetail.parse_info.is_supported ? '支持' : '不支持' }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 重新上传文件 -->
    <input
      ref="fileInput"
      type="file"
      style="display: none"
      @change="handleReupload"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  ReloadOutlined,
  DeleteOutlined,
  MoreOutlined,
  FileTextOutlined,
  UploadOutlined,
  FileOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'
import { useChatStore } from '@/stores/chat'
import {
  getSessionFiles,
  markFileForUse,
  unmarkFileForUse,
  deleteFile as deleteFileApi,
  clearSessionFiles,
  batchMarkFiles,
  batchUnmarkFiles,
  getFileInfo,
  uploadFile,
  type FileInfo,
  type FileDetailResponse
} from '@/api/chat'

const chatStore = useChatStore()

// 响应式数据
const files = ref<FileInfo[]>([])
const loading = ref(false)
const clearingAll = ref(false)
const batchLoading = ref(false)
const operatingFiles = ref<string[]>([])
const selectedFiles = ref<string[]>([])
const fileDetailVisible = ref(false)
const selectedFileDetail = ref<FileDetailResponse | null>(null)
const fileInput = ref<HTMLInputElement>()
const reuploadingFile = ref<FileInfo | null>(null)

// 计算属性
const usingCount = computed(() => files.value.filter(f => f.used).length)

// 方法
const refreshFiles = async () => {
  loading.value = true
  try {
    const response = await getSessionFiles(chatStore.sessionId)
    files.value = response.files
  } catch (error) {
    message.error('获取文件列表失败')
    console.error('Get files error:', error)
  }
  loading.value = false
}

// 监听会话变化
watch(() => chatStore.sessionId, () => {
  refreshFiles()
}, { immediate: true })

const toggleFileSelection = (fileId: string) => {
  const index = selectedFiles.value.indexOf(fileId)
  if (index > -1) {
    selectedFiles.value.splice(index, 1)
  } else {
    selectedFiles.value.push(fileId)
  }
}

const markAsUsed = async (fileId: string) => {
  operatingFiles.value.push(fileId)
  try {
    await markFileForUse(chatStore.sessionId, fileId)
    message.success('文件已标记为使用中')
    await refreshFiles()
  } catch (error) {
    message.error('标记文件失败')
    console.error('Mark file error:', error)
  }
  operatingFiles.value = operatingFiles.value.filter(id => id !== fileId)
}

const unmarkAsUsed = async (fileId: string) => {
  operatingFiles.value.push(fileId)
  try {
    await unmarkFileForUse(chatStore.sessionId, fileId)
    message.success('已取消文件的使用标记')
    await refreshFiles()
  } catch (error) {
    message.error('取消标记失败')
    console.error('Unmark file error:', error)
  }
  operatingFiles.value = operatingFiles.value.filter(id => id !== fileId)
}

const deleteFile = async (fileId: string, fileName: string) => {
  try {
    await deleteFileApi(chatStore.sessionId, fileId)
    message.success(`文件 ${fileName} 已删除`)
    await refreshFiles()
    // 从选中列表中移除
    selectedFiles.value = selectedFiles.value.filter(id => id !== fileId)
  } catch (error) {
    message.error('删除文件失败')
    console.error('Delete file error:', error)
  }
}

const clearAllFiles = async () => {
  clearingAll.value = true
  try {
    await clearSessionFiles(chatStore.sessionId)
    message.success('所有文件已清空')
    files.value = []
    selectedFiles.value = []
  } catch (error) {
    message.error('清空文件失败')
    console.error('Clear files error:', error)
  }
  clearingAll.value = false
}

const batchMarkAsUsed = async () => {
  batchLoading.value = true
  try {
    const response = await batchMarkFiles(chatStore.sessionId, selectedFiles.value)
    message.success(response.message)
    await refreshFiles()
    selectedFiles.value = []
  } catch (error) {
    message.error('批量标记失败')
    console.error('Batch mark error:', error)
  }
  batchLoading.value = false
}

const batchUnmarkAsUsed = async () => {
  batchLoading.value = true
  try {
    const response = await batchUnmarkFiles(chatStore.sessionId, selectedFiles.value)
    message.success(response.message)
    await refreshFiles()
    selectedFiles.value = []
  } catch (error) {
    message.error('批量取消标记失败')
    console.error('Batch unmark error:', error)
  }
  batchLoading.value = false
}

const viewFileInfo = async (file: FileInfo) => {
  try {
    selectedFileDetail.value = await getFileInfo(chatStore.sessionId, file.id)
    fileDetailVisible.value = true
  } catch (error) {
    message.error('获取文件详情失败')
    console.error('Get file info error:', error)
  }
}

const reuploadFile = (file: FileInfo) => {
  reuploadingFile.value = file
  fileInput.value?.click()
}

const handleReupload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file || !reuploadingFile.value) return

  try {
    // 先删除原文件
    await deleteFileApi(chatStore.sessionId, reuploadingFile.value.id)
    
    // 上传新文件
    await uploadFile(file, chatStore.sessionId)
    
    message.success(`文件 ${file.name} 重新上传成功`)
    await refreshFiles()
  } catch (error) {
    message.error('重新上传失败')
    console.error('Reupload error:', error)
  }
  
  reuploadingFile.value = null
  target.value = ''
}

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

const getFileExtension = (filename: string): string => {
  const ext = filename.split('.').pop()?.toUpperCase()
  return ext || 'FILE'
}

const getFileTypeColor = (filename: string): string => {
  const ext = filename.split('.').pop()?.toLowerCase()
  const colorMap: Record<string, string> = {
    'pdf': 'red',
    'doc': 'blue',
    'docx': 'blue',
    'txt': 'green',
    'md': 'purple',
    'json': 'orange',
    'xml': 'orange',
    'csv': 'cyan',
    'xlsx': 'green',
    'xls': 'green',
    'png': 'magenta',
    'jpg': 'magenta',
    'jpeg': 'magenta',
    'gif': 'magenta'
  }
  return colorMap[ext || ''] || 'default'
}

onMounted(() => {
  refreshFiles()
})
</script>

<style scoped>
.file-manager {
  height: 100%;
}

.file-stats {
  margin-bottom: 16px;
  padding: 8px;
  background-color: #fafafa;
  border-radius: 4px;
}

.batch-actions {
  margin-bottom: 16px;
  padding: 8px;
  background-color: #e6f7ff;
  border-radius: 4px;
  border: 1px solid #91d5ff;
}

.file-list {
  max-height: 400px;
  overflow-y: auto;
}

.file-item {
  padding: 8px 0;
}

.file-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 12px;
}

.file-selection {
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.name-text {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

.status-tag {
  flex-shrink: 0;
}

.file-meta {
  font-size: 12px;
  color: #666;
}

.file-size, .upload-time {
  color: #999;
}

.file-actions {
  flex-shrink: 0;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.danger-item {
  color: #ff4d4f !important;
}

.danger-item:hover {
  background-color: #fff2f0 !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .file-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .file-info {
    width: 100%;
  }
  
  .name-text {
    max-width: 150px;
  }
  
  .file-actions {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>